#include <stdio.h>
#include <string.h>
#include "lktsqlparser.h"

int main(int argc, char *argv[])
{
    printf ("\033[32m======================================================\033[0m\n");
    SQLPARSER_S sqlparser;
    memset (&sqlparser, 0, sizeof (sqlparser));

    FILE *fp = fopen (argv[1], "r+");
    if (NULL == fp)
    {
        printf ("fopen error\n");
        return 0;
    }

    char buffer[1024] = {0};
    while (fgets (buffer, sizeof (buffer), fp))
    {
        if (strlen(buffer) < 2)
        {
            continue;
        }
        else if ((buffer[0] == '/') && (buffer[1] == '*'))
        {
            continue;
        }
        printf ("\033[33mSQL:%s\033[0m", buffer);
        int ret = LKT_SQLPARSER_ParseSQL (0, buffer,  &sqlparser, NULL);
        if (0 != ret)
        {
            printf ("\n\n");
            continue;
        }
        memset (buffer, 0, sizeof (buffer));

        int i = 0;
        int j = 0;
        int k = 0;
        SQLPARSER_COLUMN_NODE_S *current = NULL;
        for (i = 0; i < sqlparser.statementnum; i++)
        {
            printf ("statement %d have %d nodes\n", i+1, sqlparser.statement[i]->nodeNum);

            current = sqlparser.statement[i]->header;
            while (NULL != current)
            {
                printf ("node[%d]\t", j+1);
                printf ("[value]:|%s|\t", current->value);
                printf ("[column]:|%s|\t", current->column);
                printf ("[table]:|%s|\t", current->prefixTable);
                printf ("[db]:|%s|\t", current->prefixDatabase);
                printf ("[idx]:|%d|\n", current->idx);
                printf ("[offset]:|%d|\n", current->offset);
                printf ("[isMatchPattern]:|%d|\t [matchType]:|%d|\t [isNot]:|%d|\t [isHaveEscape]:|%d|\t [escapeChar]:|%c|\n", current->isMatchPattern, current->matchPattern.matchType,
                        current->matchPattern.isHaveNotToken, current->matchPattern.isHaveEscapeChar, 
                        current->matchPattern.escapeChar);
                printf ("\tpossbile Table\n");

                for (k = 0 ; k < current->possbileTable.tableNum; k++)
                {
                    printf ("\t\t[table]:|%s|\t", current->possbileTable.tableNode[k].tableName);
                    printf ("[db]:|%s|\n", current->possbileTable.tableNode[k].dbName);
                }

                current = current->next;
                j++;
            }
            printf ("\n");
        }

        LKT_SQLPARSER_Release (&sqlparser);
    }

    fclose(fp);


    return 0;
}
